#[cfg(test)]
mod tests {
    use super::*;
    use crate::{NacosRegistry, ConsulRegistry, EurekaRegistry, AutoRemovalConfig, RemovalStrategy};
    use rustcloud_core::{ServiceRegistry, ServiceInstance, RegistryConfig, RegistryType};
    use wiremock::{MockServer, Mock, ResponseTemplate};
    use wiremock::matchers::{method, path};
    use serde_json::json;
    use tokio::time::{timeout, Duration};
    use std::sync::Arc;
    
    // ================== Nacos Registry 测试 ==================
    
    #[tokio::test]
    async fn test_nacos_registry_creation() {
        let config = RegistryConfig {
            registry_type: RegistryType::Nacos,
            server_addr: "127.0.0.1:8848".to_string(),
            namespace: Some("public".to_string()),
            group: Some("DEFAULT_GROUP".to_string()),
            username: None,
            password: None,
        };
        
        let registry = NacosRegistry::new(config);
        assert!(registry.is_ok());
    }
    
    #[tokio::test]
    async fn test_nacos_registry_invalid_type() {
        let config = RegistryConfig {
            registry_type: RegistryType::Consul,
            server_addr: "127.0.0.1:8848".to_string(),
            namespace: None,
            group: None,
            username: None,
            password: None,
        };
        
        let result = NacosRegistry::new(config);
        assert!(result.is_err());
    }
    
    #[tokio::test]
    async fn test_nacos_service_registration() {
        let mock_server = MockServer::start().await;
        
        Mock::given(method("POST"))
            .and(path("/nacos/v1/ns/instance"))
            .respond_with(ResponseTemplate::new(200).set_body_string("ok"))
            .mount(&mock_server)
            .await;
        
        let config = RegistryConfig {
            registry_type: RegistryType::Nacos,
            server_addr: mock_server.address().to_string(),
            namespace: Some("public".to_string()),
            group: Some("DEFAULT_GROUP".to_string()),
            username: None,
            password: None,
        };
        
        let registry = NacosRegistry::new(config).unwrap();
        let instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        
        let result = registry.register(instance).await;
        assert!(result.is_ok());
    }
    
    #[tokio::test]
    async fn test_nacos_service_deregistration() {
        let mock_server = MockServer::start().await;
        
        Mock::given(method("DELETE"))
            .and(path("/nacos/v1/ns/instance"))
            .respond_with(ResponseTemplate::new(200).set_body_string("ok"))
            .mount(&mock_server)
            .await;
        
        let config = RegistryConfig {
            registry_type: RegistryType::Nacos,
            server_addr: mock_server.address().to_string(),
            namespace: Some("public".to_string()),
            group: Some("DEFAULT_GROUP".to_string()),
            username: None,
            password: None,
        };
        
        let registry = NacosRegistry::new(config).unwrap();
        let instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        
        let result = registry.deregister(instance).await;
        assert!(result.is_ok());
    }
    
    #[tokio::test]
    async fn test_nacos_service_discovery() {
        let mock_server = MockServer::start().await;
        
        let response_body = json!({
            "hosts": [
                {
                    "ip": "127.0.0.1",
                    "port": 8080,
                    "weight": 1.0,
                    "healthy": true,
                    "enabled": true,
                    "metadata": {},
                    "serviceName": "test-service",
                    "clusterName": "DEFAULT",
                    "namespaceId": "public"
                }
            ]
        });
        
        Mock::given(method("GET"))
            .and(path("/nacos/v1/ns/instance/list"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&response_body))
            .mount(&mock_server)
            .await;
        
        let config = RegistryConfig {
            registry_type: RegistryType::Nacos,
            server_addr: mock_server.address().to_string(),
            namespace: Some("public".to_string()),
            group: Some("DEFAULT_GROUP".to_string()),
            username: None,
            password: None,
        };
        
        let registry = NacosRegistry::new(config).unwrap();
        let result = registry.discover("test-service").await;
        
        assert!(result.is_ok());
        let instances = result.unwrap();
        assert_eq!(instances.len(), 1);
        assert_eq!(instances[0].host, "127.0.0.1");
        assert_eq!(instances[0].port, 8080);
    }
    
    #[tokio::test]
    async fn test_nacos_health_check() {
        let mock_server = MockServer::start().await;
        
        let response_body = json!({
            "hosts": [
                {
                    "ip": "127.0.0.1",
                    "port": 8080,
                    "weight": 1.0,
                    "healthy": true,
                    "enabled": true,
                    "metadata": {},
                    "serviceName": "test-service",
                    "clusterName": "DEFAULT",
                    "namespaceId": "public"
                },
                {
                    "ip": "127.0.0.1",
                    "port": 8081,
                    "weight": 1.0,
                    "healthy": false,
                    "enabled": true,
                    "metadata": {},
                    "serviceName": "test-service",
                    "clusterName": "DEFAULT",
                    "namespaceId": "public"
                }
            ]
        });
        
        Mock::given(method("GET"))
            .and(path("/nacos/v1/ns/instance/list"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&response_body))
            .mount(&mock_server)
            .await;
        
        let config = RegistryConfig {
            registry_type: RegistryType::Nacos,
            server_addr: mock_server.address().to_string(),
            namespace: Some("public".to_string()),
            group: Some("DEFAULT_GROUP".to_string()),
            username: None,
            password: None,
        };
        
        let registry = NacosRegistry::new(config).unwrap();
        let result = registry.health_check("test-service").await;
        
        assert!(result.is_ok());
        let healthy_instances = result.unwrap();
        assert_eq!(healthy_instances.len(), 1);
        assert!(healthy_instances[0].healthy);
    }
    
    #[tokio::test]
    async fn test_nacos_registration_failure() {
        let mock_server = MockServer::start().await;
        
        Mock::given(method("POST"))
            .and(path("/nacos/v1/ns/instance"))
            .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
            .mount(&mock_server)
            .await;
        
        let config = RegistryConfig {
            registry_type: RegistryType::Nacos,
            server_addr: mock_server.address().to_string(),
            namespace: Some("public".to_string()),
            group: Some("DEFAULT_GROUP".to_string()),
            username: None,
            password: None,
        };
        
        let registry = NacosRegistry::new(config).unwrap();
        let instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        
        let result = registry.register(instance).await;
        assert!(result.is_err());
    }
    
    // ================== Consul Registry 测试 ==================
    
    #[tokio::test]
    async fn test_consul_registry_creation() {
        let config = RegistryConfig {
            registry_type: RegistryType::Consul,
            server_addr: "127.0.0.1:8500".to_string(),
            namespace: None,
            group: None,
            username: None,
            password: None,
        };
        
        let registry = ConsulRegistry::new(config);
        assert!(registry.is_ok());
    }
    
    #[tokio::test]
    async fn test_consul_service_registration() {
        let mock_server = MockServer::start().await;
        
        Mock::given(method("PUT"))
            .and(path("/v1/agent/service/register"))
            .respond_with(ResponseTemplate::new(200))
            .mount(&mock_server)
            .await;
        
        let config = RegistryConfig {
            registry_type: RegistryType::Consul,
            server_addr: mock_server.address().to_string(),
            namespace: None,
            group: None,
            username: None,
            password: None,
        };
        
        let registry = ConsulRegistry::new(config).unwrap();
        let instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        
        let result = registry.register(instance).await;
        assert!(result.is_ok());
    }
    
    #[tokio::test]
    async fn test_consul_service_discovery() {
        let mock_server = MockServer::start().await;
        
        let response_body = json!([
            {
                "ServiceID": "test-service-1",
                "ServiceName": "test-service",
                "ServiceAddress": "127.0.0.1",
                "ServicePort": 8080,
                "ServiceTags": [],
                "ServiceMeta": {},
                "Checks": [
                    {
                        "Status": "passing"
                    }
                ]
            }
        ]);
        
        Mock::given(method("GET"))
            .and(path("/v1/health/service/test-service"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&response_body))
            .mount(&mock_server)
            .await;
        
        let config = RegistryConfig {
            registry_type: RegistryType::Consul,
            server_addr: mock_server.address().to_string(),
            namespace: None,
            group: None,
            username: None,
            password: None,
        };
        
        let registry = ConsulRegistry::new(config).unwrap();
        let result = registry.discover("test-service").await;
        
        assert!(result.is_ok());
        let instances = result.unwrap();
        assert_eq!(instances.len(), 1);
        assert_eq!(instances[0].host, "127.0.0.1");
        assert_eq!(instances[0].port, 8080);
    }
    
    // ================== Eureka Registry 测试 ==================
    
    #[tokio::test]
    async fn test_eureka_registry_creation() {
        let config = RegistryConfig {
            registry_type: RegistryType::Eureka,
            server_addr: "127.0.0.1:8761".to_string(),
            namespace: None,
            group: None,
            username: None,
            password: None,
        };
        
        let registry = EurekaRegistry::new(config);
        assert!(registry.is_ok());
    }
    
    #[tokio::test]
    async fn test_eureka_service_registration() {
        let mock_server = MockServer::start().await;
        
        Mock::given(method("POST"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&mock_server)
            .await;

    // ================ 补充更全面的注册中心测试 ================
    
    // 针对 InMemoryRegistry 的全面测试
    #[tokio::test]
    async fn test_in_memory_registry_comprehensive() {
        let registry = InMemoryRegistry::new();
        
        // 测试注册多个不同的服务实例
        let test_instances = [
            ServiceInstance::new("user-service", "127.0.0.1", 8080, "http"),
            ServiceInstance::new("user-service", "127.0.0.1", 8081, "http"),
            ServiceInstance::new("user-service", "192.168.1.10", 8080, "http"),
            ServiceInstance::new("order-service", "127.0.0.1", 9090, "http"),
            ServiceInstance::new("order-service", "127.0.0.1", 9091, "grpc"),
        ];
        
        // 注册所有实例
        for instance in &test_instances {
            let result = registry.register(instance.clone()).await;
            assert!(result.is_ok(), "Registration should succeed for instance: {:?}", instance);
        }
        
        // 测试服务发现
        let user_instances = registry.discover("user-service").await.unwrap();
        assert_eq!(user_instances.len(), 3, "Should have 3 user-service instances");
        
        let order_instances = registry.discover("order-service").await.unwrap();
        assert_eq!(order_instances.len(), 2, "Should have 2 order-service instances");
        
        // 测试不存在的服务
        let nonexistent_instances = registry.discover("nonexistent-service").await.unwrap();
        assert_eq!(nonexistent_instances.len(), 0, "Should have 0 instances for nonexistent service");
        
        // 测试重复注册相同实例（应该不会重复添加）
        let duplicate_instance = ServiceInstance::new("user-service", "127.0.0.1", 8080, "http");
        registry.register(duplicate_instance).await.unwrap();
        
        let user_instances_after_duplicate = registry.discover("user-service").await.unwrap();
        assert_eq!(user_instances_after_duplicate.len(), 3, "Should still have 3 user-service instances after duplicate registration");
        
        // 测试注销服务实例
        let instance_to_deregister = ServiceInstance::new("user-service", "127.0.0.1", 8080, "http");
        registry.deregister(instance_to_deregister).await.unwrap();
        
        let user_instances_after_deregister = registry.discover("user-service").await.unwrap();
        assert_eq!(user_instances_after_deregister.len(), 2, "Should have 2 user-service instances after deregistration");
        
        // 验证剩余的实例是正确的
        let remaining_ports: Vec<u16> = user_instances_after_deregister.iter().map(|i| i.port).collect();
        assert!(remaining_ports.contains(&8081));
        assert!(!remaining_ports.contains(&8080));
    }
    
    // 针对 InMemoryRegistry 健康检查测试
    #[tokio::test]
    async fn test_in_memory_registry_health_check() {
        let registry = InMemoryRegistry::new();
        
        // 注册健康和不健康的实例
        let mut healthy_instance = ServiceInstance::new("service", "127.0.0.1", 8080, "http");
        healthy_instance.set_healthy(true);
        
        let mut unhealthy_instance = ServiceInstance::new("service", "127.0.0.1", 8081, "http");
        unhealthy_instance.set_healthy(false);
        
        registry.register(healthy_instance).await.unwrap();
        registry.register(unhealthy_instance).await.unwrap();
        
        // discover方法应该只返回健康的实例
        let instances = registry.discover("service").await.unwrap();
        assert_eq!(instances.len(), 1, "Should only return healthy instances");
        assert_eq!(instances[0].port, 8080);
        assert!(instances[0].healthy);
        
        // health_check方法应该返回相同的结果
        let health_instances = registry.health_check("service").await.unwrap();
        assert_eq!(health_instances.len(), 1);
        assert_eq!(health_instances[0].port, 8080);
    }
    
    // 针对 RegistryFactory 的全面测试
    #[test]
    fn test_registry_factory_comprehensive() {
        // 测试创建Nacos注册中心
        let nacos_config = RegistryConfig {
            registry_type: RegistryType::Nacos,
            server_addr: "127.0.0.1:8848".to_string(),
            namespace: Some("public".to_string()),
            group: Some("DEFAULT_GROUP".to_string()),
            username: Some("nacos".to_string()),
            password: Some("nacos".to_string()),
        };
        
        let nacos_registry = RegistryFactory::create(nacos_config);
        assert!(nacos_registry.is_ok(), "Nacos registry creation should succeed");
        
        // 测试创建Consul注册中心
        let consul_config = RegistryConfig {
            registry_type: RegistryType::Consul,
            server_addr: "127.0.0.1:8500".to_string(),
            namespace: None,
            group: None,
            username: None,
            password: None,
        };
        
        let consul_registry = RegistryFactory::create(consul_config);
        assert!(consul_registry.is_ok(), "Consul registry creation should succeed");
        
        // 测试创建Eureka注册中心
        let eureka_config = RegistryConfig {
            registry_type: RegistryType::Eureka,
            server_addr: "127.0.0.1:8761".to_string(),
            namespace: Some("MYAPP".to_string()),
            group: None,
            username: None,
            password: None,
        };
        
        let eureka_registry = RegistryFactory::create(eureka_config);
        assert!(eureka_registry.is_ok(), "Eureka registry creation should succeed");
    }
    
    // 针对 CompositeRegistry 的全面测试
    #[tokio::test]
    async fn test_composite_registry_comprehensive() {
        let mut composite = CompositeRegistry::new();
        
        // 添加多个注册中心
        let memory_registry1 = Arc::new(InMemoryRegistry::new());
        let memory_registry2 = Arc::new(InMemoryRegistry::new());
        
        composite.add_registry("registry1".to_string(), memory_registry1.clone());
        composite.add_registry("registry2".to_string(), memory_registry2.clone());
        
        let test_instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        
        // 测试注册（应该在所有注册中心中注册）
        let register_result = composite.register(test_instance.clone()).await;
        assert!(register_result.is_ok(), "Composite registration should succeed");
        
        // 验证实例在所有子注册中心中都存在
        let instances1 = memory_registry1.discover("test-service").await.unwrap();
        let instances2 = memory_registry2.discover("test-service").await.unwrap();
        
        assert_eq!(instances1.len(), 1, "Instance should be in registry1");
        assert_eq!(instances2.len(), 1, "Instance should be in registry2");
        
        // 测试发现（应该返回来自所有注册中心的实例）
        let discovered_instances = composite.discover("test-service").await.unwrap();
        assert_eq!(discovered_instances.len(), 2, "Should discover instances from both registries");
        
        // 测试注销（应该从所有注册中心中注销）
        let deregister_result = composite.deregister(test_instance).await;
        assert!(deregister_result.is_ok(), "Composite deregistration should succeed");
        
        // 验证实例从所有子注册中心中都被移除
        let instances1_after = memory_registry1.discover("test-service").await.unwrap();
        let instances2_after = memory_registry2.discover("test-service").await.unwrap();
        
        assert_eq!(instances1_after.len(), 0, "Instance should be removed from registry1");
        assert_eq!(instances2_after.len(), 0, "Instance should be removed from registry2");
    }
    
    // 针对不同注册中心类型的配置验证测试
    #[test]
    fn test_registry_config_validation() {
        // 测试Nacos配置验证
        let nacos_config = RegistryConfig {
            registry_type: RegistryType::Nacos,
            server_addr: "127.0.0.1:8848".to_string(),
            namespace: Some("production".to_string()),
            group: Some("USER_GROUP".to_string()),
            username: None,
            password: None,
        };
        
        let nacos_registry = NacosRegistry::new(nacos_config);
        assert!(nacos_registry.is_ok());
        
        // 测试错误的注册中心类型
        let wrong_config = RegistryConfig {
            registry_type: RegistryType::Consul, // 错误类型
            server_addr: "127.0.0.1:8848".to_string(),
            namespace: None,
            group: None,
            username: None,
            password: None,
        };
        
        let nacos_with_wrong_config = NacosRegistry::new(wrong_config);
        assert!(nacos_with_wrong_config.is_err(), "Should fail with wrong registry type");
        
        // 测试Consul配置验证
        let consul_config = RegistryConfig {
            registry_type: RegistryType::Consul,
            server_addr: "consul.example.com:8500".to_string(),
            namespace: None,
            group: None,
            username: Some("consul-user".to_string()),
            password: Some("consul-pass".to_string()),
        };
        
        let consul_registry = ConsulRegistry::new(consul_config);
        assert!(consul_registry.is_ok());
        
        // 测试Eureka配置验证
        let eureka_config = RegistryConfig {
            registry_type: RegistryType::Eureka,
            server_addr: "http://eureka.example.com:8761".to_string(),
            namespace: Some("MYAPP".to_string()),
            group: None,
            username: None,
            password: None,
        };
        
        let eureka_registry = EurekaRegistry::new(eureka_config);
        assert!(eureka_registry.is_ok());
    }
    
    // 针对服务实例不同参数的注册测试
    #[tokio::test]
    async fn test_service_instance_registration_variations() {
        let registry = InMemoryRegistry::new();
        
        // 测试不同协议的服务实例
        let http_instance = ServiceInstance::new("web-service", "127.0.0.1", 8080, "http");
        let https_instance = ServiceInstance::new("secure-service", "127.0.0.1", 8443, "https");
        let grpc_instance = ServiceInstance::new("api-service", "127.0.0.1", 9090, "grpc");
        let tcp_instance = ServiceInstance::new("tcp-service", "127.0.0.1", 1234, "tcp");
        let udp_instance = ServiceInstance::new("udp-service", "127.0.0.1", 5678, "udp");
        
        let instances = [http_instance, https_instance, grpc_instance, tcp_instance, udp_instance];
        
        for instance in &instances {
            let result = registry.register(instance.clone()).await;
            assert!(result.is_ok(), "Registration should succeed for {:?} instance", instance.scheme);
        }
        
        // 测试带权重的服务实例
        let mut weighted_instance = ServiceInstance::new("weighted-service", "127.0.0.1", 8080, "http");
        weighted_instance.set_weight(2.5).unwrap();
        
        let result = registry.register(weighted_instance).await;
        assert!(result.is_ok());
        
        // 测试带元数据的服务实例
        let mut metadata_instance = ServiceInstance::new("metadata-service", "127.0.0.1", 8080, "http");
        metadata_instance.add_metadata("version", "1.0.0");
        metadata_instance.add_metadata("region", "us-west-1");
        metadata_instance.add_metadata("datacenter", "dc1");
        
        let result = registry.register(metadata_instance).await;
        assert!(result.is_ok());
        
        // 测试带环境信息的服务实例
        let env_instance = ServiceInstance::with_group_and_env(
            "env-service", "127.0.0.1", 8080, "http",
            Some("production".to_string()),
            Some("default".to_string()),
            Some("prod".to_string()),
        );
        
        let result = registry.register(env_instance).await;
        assert!(result.is_ok());
    }
    
    // 针对健康状态变化的测试
    #[tokio::test]
    async fn test_health_status_changes() {
        let registry = InMemoryRegistry::new();
        
        // 注册健康的实例
        let mut instance = ServiceInstance::new("dynamic-service", "127.0.0.1", 8080, "http");
        instance.set_healthy(true);
        registry.register(instance.clone()).await.unwrap();
        
        // 验证健康实例可以被发现
        let healthy_instances = registry.discover("dynamic-service").await.unwrap();
        assert_eq!(healthy_instances.len(), 1);
        
        // 修改实例健康状态并重新注册
        instance.set_healthy(false);
        registry.register(instance.clone()).await.unwrap();
        
        // 验证不健康实例不会被发现
        let unhealthy_instances = registry.discover("dynamic-service").await.unwrap();
        assert_eq!(unhealthy_instances.len(), 0, "Unhealthy instances should not be discovered");
        
        // 恢复健康状态
        instance.set_healthy(true);
        registry.register(instance).await.unwrap();
        
        // 验证健康实例再次可以被发现
        let recovered_instances = registry.discover("dynamic-service").await.unwrap();
        assert_eq!(recovered_instances.len(), 1);
    }
            .await;
        
        let config = RegistryConfig {
            registry_type: RegistryType::Eureka,
            server_addr: mock_server.address().to_string(),
            namespace: None,
            group: None,
            username: None,
            password: None,
        };
        
        let registry = EurekaRegistry::new(config).unwrap();
        let instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        
        let result = registry.register(instance).await;
        assert!(result.is_ok());
    }
    
    #[tokio::test]
    async fn test_eureka_service_discovery() {
        let mock_server = MockServer::start().await;
        
        let response_body = json!({
            "applications": {
                "application": [
                    {
                        "name": "TEST-SERVICE",
                        "instance": [
                            {
                                "instanceId": "test-service-1",
                                "hostName": "127.0.0.1",
                                "app": "TEST-SERVICE",
                                "ipAddr": "127.0.0.1",
                                "status": "UP",
                                "port": {
                                    "$": 8080,
                                    "@enabled": "true"
                                },
                                "securePort": {
                                    "$": 443,
                                    "@enabled": "false"
                                }
                            }
                        ]
                    }
                ]
            }
        });
        
        Mock::given(method("GET"))
            .and(path("/eureka/apps/test-service"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&response_body))
            .mount(&mock_server)
            .await;
        
        let config = RegistryConfig {
            registry_type: RegistryType::Eureka,
            server_addr: mock_server.address().to_string(),
            namespace: None,
            group: None,
            username: None,
            password: None,
        };
        
        let registry = EurekaRegistry::new(config).unwrap();
        let result = registry.discover("test-service").await;
        
        assert!(result.is_ok());
        let instances = result.unwrap();
        assert_eq!(instances.len(), 1);
        assert_eq!(instances[0].host, "127.0.0.1");
        assert_eq!(instances[0].port, 8080);
    }
    
    // ================== Health Checker 测试 ==================
    
    #[tokio::test]
    async fn test_health_check_config_creation() {
        let config = rustcloud_core::HealthCheck {
            check_type: rustcloud_core::HealthCheckType::Http {
                path: "/health".to_string(),
                method: "GET".to_string(),
            },
            endpoint: "http://localhost:8080/health".to_string(),
            interval: Duration::from_secs(30),
            timeout: Duration::from_secs(5),
            failure_threshold: 3,
            success_threshold: 2,
        };
        
        assert_eq!(config.interval, Duration::from_secs(30));
        assert_eq!(config.timeout, Duration::from_secs(5));
        assert_eq!(config.failure_threshold, 3);
        assert_eq!(config.success_threshold, 2);
    }
    
    #[tokio::test]
    async fn test_health_check_types() {
        // 测试 HTTP 类型
        let http_config = rustcloud_core::HealthCheckType::Http {
            path: "/health".to_string(),
            method: "GET".to_string(),
        };
        
        match http_config {
            rustcloud_core::HealthCheckType::Http { path, method } => {
                assert_eq!(path, "/health");
                assert_eq!(method, "GET");
            }
            _ => panic!("Expected HTTP health check type"),
        }
        
        // 测试 TCP 类型
        let tcp_config = rustcloud_core::HealthCheckType::Tcp;
        match tcp_config {
            rustcloud_core::HealthCheckType::Tcp => {
                // 正确的 TCP 类型
            }
            _ => panic!("Expected TCP health check type"),
        }
    }
    
    // ================== Auto Removal 测试 ==================
    
    #[tokio::test]
    async fn test_auto_removal_config_creation() {
        let config = AutoRemovalConfig {
            enabled: true,
            strategy: RemovalStrategy::ConsecutiveFailures { threshold: 3 },
            check_interval: Duration::from_secs(30),
            cooldown_period: Duration::from_secs(120),
            allow_remove_last_instance: false,
            min_instances: 1,
        };
        
        assert!(config.enabled);
        assert_eq!(config.cooldown_period, Duration::from_secs(120));
        assert!(!config.allow_remove_last_instance);
        assert_eq!(config.min_instances, 1);
        assert_eq!(config.check_interval, Duration::from_secs(30));
    }
    
    // ================== Mock Registry 测试 ==================
    
    // Mock Registry 用于测试
    struct MockRegistry {
        instances: Arc<tokio::sync::Mutex<std::collections::HashMap<String, Vec<ServiceInstance>>>>,
        should_fail: bool,
    }
    
    impl MockRegistry {
        fn new(should_fail: bool) -> Self {
            Self {
                instances: Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new())),
                should_fail,
            }
        }
    }
    
    #[async_trait::async_trait]
    impl ServiceRegistry for MockRegistry {
        async fn register(&self, instance: ServiceInstance) -> rustcloud_core::ServiceResult<()> {
            if self.should_fail {
                return Err(rustcloud_core::ServiceError::RegistryError("Mock failure".to_string()));
            }
            
            let mut instances = self.instances.lock().await;
            instances.entry(instance.service_id.clone())
                .or_insert_with(Vec::new)
                .push(instance);
            Ok(())
        }
        
        async fn deregister(&self, instance: ServiceInstance) -> rustcloud_core::ServiceResult<()> {
            if self.should_fail {
                return Err(rustcloud_core::ServiceError::RegistryError("Mock failure".to_string()));
            }
            
            let mut instances = self.instances.lock().await;
            if let Some(service_instances) = instances.get_mut(&instance.service_id) {
                service_instances.retain(|i| !(i.host == instance.host && i.port == instance.port));
            }
            Ok(())
        }
        
        async fn discover(&self, service_name: &str) -> rustcloud_core::ServiceResult<Vec<ServiceInstance>> {
            if self.should_fail {
                return Err(rustcloud_core::ServiceError::RegistryError("Mock failure".to_string()));
            }
            
            let instances = self.instances.lock().await;
            Ok(instances.get(service_name).cloned().unwrap_or_default())
        }
        
        async fn health_check(&self, service_name: &str) -> rustcloud_core::ServiceResult<Vec<ServiceInstance>> {
            let instances = self.discover(service_name).await?;
            Ok(instances.into_iter().filter(|i| i.healthy).collect())
        }
        
        async fn watch(&self, _service_name: &str) -> rustcloud_core::ServiceResult<Box<dyn rustcloud_core::ServiceWatcher + Send>> {
            Err(rustcloud_core::ServiceError::NotImplemented("Watch not implemented for mock registry".to_string()))
        }
    }
    
    #[tokio::test]
    async fn test_mock_registry() {
        let registry = MockRegistry::new(false);
        let instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        
        // 测试注册
        let result = registry.register(instance.clone()).await;
        assert!(result.is_ok());
        
        // 测试服务发现
        let discovered = registry.discover("test-service").await.unwrap();
        assert_eq!(discovered.len(), 1);
        assert_eq!(discovered[0].service_id, "test-service");
        
        // 测试健康检查
        let healthy = registry.health_check("test-service").await.unwrap();
        assert_eq!(healthy.len(), 1);
        
        // 测试取消注册
        let result = registry.deregister(instance).await;
        assert!(result.is_ok());
        
        let discovered = registry.discover("test-service").await.unwrap();
        assert_eq!(discovered.len(), 0);
    }
    
    #[tokio::test]
    async fn test_mock_registry_failure() {
        let registry = MockRegistry::new(true);
        let instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        
        let result = registry.register(instance).await;
        assert!(result.is_err());
        
        let result = registry.discover("test-service").await;
        assert!(result.is_err());
    }
    
    // ================== 集成测试 ==================
    
    #[tokio::test]
    async fn test_registry_timeout_handling() {
        let config = RegistryConfig {
            registry_type: RegistryType::Nacos,
            server_addr: "127.0.0.1:9999".to_string(), // 不存在的端口
            namespace: Some("public".to_string()),
            group: Some("DEFAULT_GROUP".to_string()),
            username: None,
            password: None,
        };
        
        let registry = NacosRegistry::new(config).unwrap();
        let instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        
        // 测试超时处理
        let result = timeout(Duration::from_secs(5), registry.register(instance)).await;
        
        // 应该是超时或者连接失败
        assert!(result.is_err() || (result.is_ok() && result.unwrap().is_err()));
    }
    
    #[tokio::test]
    async fn test_registry_config_validation() {
        // 测试空地址
        let config = RegistryConfig {
            registry_type: RegistryType::Nacos,
            server_addr: "".to_string(),
            namespace: None,
            group: None,
            username: None,
            password: None,
        };
        
        let result = NacosRegistry::new(config);
        assert!(result.is_err());
    }
    
    #[tokio::test]
    async fn test_service_instance_metadata_handling() {
        let mock_registry = MockRegistry::new(false);
        let mut instance = ServiceInstance::new("test-service", "127.0.0.1", 8080, "http");
        
        // 添加元数据
        instance.add_metadata("version", "1.0.0");
        instance.add_metadata("environment", "test");
        instance.set_weight(2.0).unwrap();
        
        let result = mock_registry.register(instance.clone()).await;
        assert!(result.is_ok());
        
        let discovered = mock_registry.discover("test-service").await.unwrap();
        assert_eq!(discovered.len(), 1);
        assert_eq!(discovered[0].get_metadata("version"), Some("1.0.0"));
        assert_eq!(discovered[0].get_metadata("environment"), Some("test"));
        assert_eq!(discovered[0].weight, 2.0);
    }
}